package com.kvest.scanrecognizer.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.kvest.scanrecognizer.R;
import com.kvest.scanrecognizer.core.Settings;

import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: roman
 * Date: 11/11/13
 * Time: 7:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class SettingsFragment extends Fragment {
    public static final Pattern PATH_PATTERN = Pattern.compile("^(/)?([^/\0]+(/)?)+$");

    EditText workingDirectory;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.settings_fragment, container, false);

        workingDirectory = (EditText)root.findViewById(R.id.working_dir);
        workingDirectory.setText(Settings.getInstance(getActivity()).getShortWorkingDirectory());

        root.findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });

        return root;
    }

    private void save() {
        if (isDataValid()) {
            Settings settings = Settings.getInstance(getActivity());
            settings.setWorkingDirectory(workingDirectory.getText().toString());
            settings.save(getActivity());

            getActivity().finish();
        }
    }

    private boolean isDataValid() {
        boolean result = true;
        if (!PATH_PATTERN.matcher(workingDirectory.getText().toString()).matches()) {
            workingDirectory.setError(getString(R.string.invalid_dir_path));
            result = false;
        }
        return result;
    }
}
